package com.tlgen.rpc.config;

import com.tlgen.rpc.annotation.Fetch;
import com.tlgen.rpc.utils.ScanUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.List;

public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(@NotNull AnnotationMetadata importingClassMetadata,
                                        @NotNull BeanDefinitionRegistry registry) {
        List<String> classesWithAnnotation = ScanUtils.getClassesWithAnnotation(Fetch.class);
        for (String completeClassName : classesWithAnnotation) {
            try {
                Class<?> clazz = Class.forName(completeClassName);
                // beanName 是 interface 接口名
                BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
                AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
                // class 替换为 FetchFactoryBean 类
                beanDefinition.setBeanClass(FetchFactoryBean.class);
                // 参数传递
                beanDefinition.getPropertyValues().add("fetchInterface", clazz.getName());
                // 注册到容器 beanName 是接口全名 beanClass 替换成 FetchFactoryBean
                registry.registerBeanDefinition(clazz.getName(), beanDefinition);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
